package com.utils
{
	import com.org.adobe.serialization.json.JSON;
	import com.org.zip.ZipEntry;
	import com.org.zip.ZipFile;
	import com.view.Vision;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	import flash.utils.setTimeout;
	
	/**
	 * 加载zip压缩包内的JSON文件
	 * @author Mr.Lu
	 * <ul> 
	 * <li><strong>第一步:设置相关参数</strong></li>
	 * <li>prefix:如果是网络路径需要设置前缀“assets”之前的内容;</li>
	 * <li>_zipPath:"assets/data/" 前缀</li>
	 * <br /><br />
	 * <li><strong>第二步:设置加载列表</strong></li>
	 * <li>startLoad(nameList) 将要加在的json文件放入数组内传入</li>
	 * </ul>
	 */	
	public class ZipUtil
	{
		public static var prefix:String = '';
		private static var _designData:Object = {};//资源池
		private static var _stringSourceBox:Object = {};//观察json文件内部结构用
		private static var loadZipUtil:ZipUtil;
		
		private var _zipPath:String = 'assets/data/';
		private var _loaderOver:Boolean = false;
		private var _loadZipCallBack:Function = new Function();
		private var _urlStream:URLStream;
		private var _totalFileNum:int;
		private var _nowLoadFileName:String;
		private var _designList:Array = [];
		private var _zipFile:ZipFile;
		private var _loadProgressBar:LoadProgressBar;
		
		public function ZipUtil()
		{
			if(!loadZipUtil) loadZipUtil = this;
			if(!_loadProgressBar){
				_loadProgressBar = new LoadProgressBar(Vision.stage);
				Vision.addView(Vision.UNSTABLE,_loadProgressBar);
			}
		}
		
		public static function get instance():ZipUtil{
			return loadZipUtil || new ZipUtil();
		}
		
		/**
		 * 开始加载 
		 * @param params 压缩包名称
		 */		
		public function startLoad(...params):void
		{
			_designList = params;
			_totalFileNum = _designList.length;
			if(!_urlStream){
				_urlStream = new URLStream();
				_urlStream.addEventListener(Event.COMPLETE,onCompleteHandler);
				_urlStream.addEventListener(IOErrorEvent.IO_ERROR,onErrorHandler);
				_urlStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onErrorHandler);
				_urlStream.addEventListener(ProgressEvent.PROGRESS,onProgressHandler);
			}
			_nowLoadFileName = _designList.pop();
			loopLoadDesign(_nowLoadFileName);
		}
		
		private function loopLoadDesign(name:String):void
		{
			_urlStream.load(new URLRequest(prefix + _zipPath + name + '.zip'));
		}
		
		protected function onProgressHandler(e:ProgressEvent):void
		{
			//trace(e.bytesLoaded,e.bytesTotal,_nowLoadFileName);
			_loadProgressBar.loadProgress(e.bytesLoaded,e.bytesTotal,_totalFileNum,_nowLoadFileName);
		}
		
		protected function onErrorHandler(e:SecurityErrorEvent):void
		{
			trace('加载出错：' + e.text);
		}
		
		protected function onCompleteHandler(e:Event):void
		{
			_zipFile = new ZipFile(URLStream(e.target));
			for (var i:int = 0; i < _zipFile.entries.length; i++) 
			{
				var entry:ZipEntry= _zipFile.entries[i];
				var byteArray:ByteArray = _zipFile.getInput(entry);    
				var keyName:String = String(entry.name).split('.')[0];
				
				_designData[keyName] = dataArrayFormat(com.org.adobe.serialization.json.JSON.decode(byteArray.toString()));//转化为数组
				_stringSourceBox[keyName] = byteArray.toString();//转化为数组
				//trace('【' + keyName + '】读取完毕！');
			}
			
			if(_designList.length > 0){
				_nowLoadFileName = _designList.pop();
				loopLoadDesign(_nowLoadFileName);
			}else{
				_loaderOver = true;
				_loadZipCallBack();
			}
		}
		
		/**将Object转化成Array*/		
		private function dataArrayFormat(target:Object):Array
		{
			var tempArr:Array = [];
			for(var key:* in target){
				tempArr.push({key:key,value:target[key]});
			}
			return tempArr;
		}
		
		
		
		
		
		
		
		
		
		/**
		 * ///////////////////////////////////////////////
		 * 根据json文件名获取json数据
		 * ///////////////////////////////////////////////
		 * @param name json文件名
		 * @param key 每一项对应主键
		 */		
		public function load(name:String,key:* = null):*
		{
			if(!_loaderOver) throw Error('资源尚未加载完毕!');
			if(!key){
				return _designData[name];
			}else{
				return getResultData(_designData[name],key);
			}
		}
		
		/**类型不确定,可能是Array也可能是Object*/		
		private function getResultData(target:Array,key:* = null):*
		{
			for (var i:int = 0; i < target.length; i++) 
			{
				if(target[i]['key'] == key) return target[i].value;
			}
			return null;
		}
		
		
		
		/**打印指定json文件内部数据结构*/
		public function traceJsonStructure(name:String):void
		{
			if(!_loaderOver) throw Error('资源尚未加载完毕!');
			trace(_stringSourceBox[name]);
		}
		
		
		
		
		
		
		
		
		/**加载完毕调用此函数*/		
		public function set loadZipCallBack(value:Function):void
		{
			_loadZipCallBack = value;
		}
		
	}
}